package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.SoulReport;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class SoulReportApiImpl implements SoulReportApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ObjectId findNewReport(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        query.limit(1).with(Sort.by(Sort.Order.desc("created")));
        SoulReport soulReport = mongoTemplate.findOne(query, SoulReport.class);
        return soulReport == null ? null : soulReport.getId();
    }

    @Override
    public ObjectId save(SoulReport soulReport) {
        SoulReport report = mongoTemplate.save(soulReport);
        return report.getId();
    }

    @Override
    public SoulReport findById(String id) {
        return mongoTemplate.findById(id, SoulReport.class);
    }

    @Override
    public List<Long> findFriend(String id) {
        SoulReport soulReport = findById(id);
        int max = soulReport.getScore() + 10;
        int min = soulReport.getScore() - 10;
        Query query = Query.query(Criteria.where("score").gt(min).lt(max));
        List<SoulReport> soulReports = mongoTemplate.find(query, SoulReport.class);
        if (soulReports.size() > 0) {
            return soulReports.stream().map(SoulReport::getUserId).collect(Collectors.toList());
        }
        List<Long> ids = new ArrayList<>();
        ids.add(3l);
        ids.add(5l);
        ids.add(7l);
        return ids;
    }
}
